# Name: JoinClimateGrid.py - MCBS 10/08/2014
# Description: Joins climate info to grid. 

# Joining climate information for such an extensive grid (>2x10^6 points) has turned out to be 
# infeasible with the current version of ArcGIS, especially because there are many 4x12 rasters to be matched.
# The idea is to extract values for a coarser grid (5km?), which should be 25x faster. 

# import system module
import arcpy
from arcpy import env
from arcpy.sa import *

# Set workspace environment:
#env.workspace = "Rasters.gdb"
env.workspace = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\Rasters.gdb"
env.overwriteOutput = True
arcpy.CheckOutExtension("Spatial")

# Folder to store tables:
PathForTables = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\Tables"

# Input grid:
GridCoarseName      = "G5kmMiRWGS"
GridCoarseCellName  = GridCoarseName + "Cell"
FinalGridName       = "G1kmMiRWGS"
GridMatchFeat       = "G1kmG5kmWGS"
GridCoarseFID       = "G5kmMiR_FID"

FieldsGridMatch   = arcpy.FieldMappings()
FieldsGridMatch.addTable(GridCoarseCellName)
x = FieldsGridMatch.findFieldMapIndex("Join_Count")
FieldsGridMatch.removeFieldMap(x)

FieldsGridMatch.addTable(FinalGridName)
x = FieldsGridMatch.findFieldMapIndex("Join_Count")
FieldsGridMatch.removeFieldMap(x)

print " Creating match between coarse and thin grids ..."
# Create Match between coarse grid and final grid:
arcpy.SpatialJoin_analysis(FinalGridName, GridCoarseCellName, GridMatchFeat, "#", "#", FieldsGridMatch)

# Delete unused fields from GridMatchFeat
arcpy.DeleteField_management(GridMatchFeat, ["TARGET_FID","TARGET_FID_1","Join_Count","Shape_Area_1","Shape_Length_1"])

# List of climate variables:
#ClimateVar = ["prec", "tmax", "tmin", "tmean"]
#Months     = range(1,13)

ClimateVar = ["prec","tmean"]
Months = range(1,13)

for clim in ClimateVar:
	# Create list of rasters and variables names for ExtractMultiValuesToPoints
	ListToExtract = [[clim + str(Months[0]),clim + str(Months[0])]]
	ListToMatch   = [clim + str(Months[0])]
	for m in Months[1:len(Months)]:
		ClimateRaster = clim + str(m)
		ListToExtract.append( [ClimateRaster,ClimateRaster] )
		ListToMatch.append(ClimateRaster)
		
	GridClimName = 	GridCoarseName + clim
	arcpy.CopyFeatures_management(GridCoarseName, GridClimName)
	ExtractMultiValuesToPoints(GridClimName,ListToExtract, "NONE")
	
	GridMatchClim = GridMatchFeat + clim
	arcpy.CopyFeatures_management(GridMatchFeat, GridMatchClim)
	arcpy.JoinField_management(GridMatchClim, GridCoarseFID, GridClimName, GridCoarseFID, ListToMatch)
	
	print " Writing table ... "
	TableClimName    = GridMatchClim + ".dbf"
	arcpy.TableToTable_conversion(GridMatchClim, PathForTables, TableClimName)
	print TableClimName + " written."


# Do it for slope and altitude...	
# NewAltitudeName = "Altitude"
# NewSlopeName    = "Slope"
# arcpy.CopyRaster_management("altPrj_33",NewAltitudeName)
# arcpy.Mosaic_management("altPrj_34",NewAltitudeName,"","", "", "", "", "", "NONE")
# outSlope = Slope(NewAltitudeName, "DEGREE")
# outSlope.save(NewSlopeName)
